package v2

import (
	"log"
	"mindonmap/pkgs/e"
	"mindonmap/validation"
	"net/http"

	"github.com/gin-gonic/gin"

	"mindonmap/models"
)

// 获取单个分享脑图
func GetMindShare(c *gin.Context) {
	var json models.MindShare
	if err := c.BindJSON(&json); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": e.INVALID_PARAMS,
			"msg":  e.GetMsg(e.INVALID_PARAMS),
			"data": make(map[string]interface{}),
		})
		return
	}

	valid := validation.Validation{}
	valid.Required(json.Shareid, "shareid").Message("不能为空")

	code := e.INVALID_PARAMS
	var data models.MindShare
	var datas models.Mindmap
	jsonecho := make(map[string]interface{})
	if !valid.HasErrors() {
		if models.ExistMindShareByID(json.Shareid) {
			data = models.GetMindShare(json.Shareid)
			datas = models.GetMindMapShare(data.Pid)
			if datas.ID > 0 {

				jsonecho["filename"] = datas.Filename
				jsonecho["version"] = datas.Version
				jsonecho["mapdata"] = datas.Mapdata
				jsonecho["checktype"] = data.Checktype
				jsonecho["expires"] = data.Expires
				jsonecho["is_edit"] = data.IsEdit
				jsonecho["acid"] = data.Acid
				jsonecho["image"] = datas.Image
				code = e.SUCCESS
			} else {
				code = e.ERROR_EXIST_PARAMS
			}
		} else {
			code = e.ERROR_EXIST_PARAMS
		}
	} else {
		for _, err := range valid.Errors {
			log.Printf("err.key: %s, err.message: %s", err.Key, err.Message)
		}
	}

	c.JSON(http.StatusOK, gin.H{
		"code": code,
		"msg":  e.GetMsg(code),
		"data": jsonecho,
	})
}

// 脑图分享校验
func VerifyMindShare(c *gin.Context) {
	var json models.MindShare
	if err := c.BindJSON(&json); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": e.INVALID_PARAMS,
			"msg":  e.GetMsg(e.INVALID_PARAMS),
			"data": make(map[string]interface{}),
		})
		return
	}

	valid := validation.Validation{}
	valid.Required(json.Pass, "pass").Message("ID必须大于0")
	valid.Required(json.Shareid, "shareid").Message("不能为空")

	code := e.INVALID_PARAMS
	if !valid.HasErrors() {
		if models.ExistMindShareVerify(json.Shareid, json.Pass) {
			code = e.SUCCESS
		} else {
			code = e.ERROR_PASS
		}
	} else {
		for _, err := range valid.Errors {
			log.Printf("err.key: %s, err.message: %s", err.Key, err.Message)
		}
	}

	c.JSON(http.StatusOK, gin.H{
		"code": code,
		"msg":  e.GetMsg(code),
		"data": make(map[string]string),
	})
}
